const {getData, insertData} = require('../model/api')
const getRandom = require('../utils/getRandom')
const jwt = require('jsonwebtoken')
module.exports = {
    // 获取验证码（注册）：获取手机号，存储手机号，生成4位随机验证码、随机头像、昵称、粉丝数、关注数，返回验证码
    async captcha(req, resp) {
        const {tel} = req.body
        console.log('tel', tel)
        let data = await getData('user', 'tel=' + tel)
        if (data && data.length > 0) {
            resp.json({
                code: 406,
                msg: '手机号被注册了！'
            })
            return
        }
        let captcha = ''
        for (let a = 0; a < 4; a++) {
            captcha += getRandom(9)
        }
        let avatar = 'http://localhost:22064/avatar/avatar' + getRandom(6, 1) + '.png'
        let nickname = '昵称' + getRandom(9)
        let fans = getRandom(10, 2)
        let follow = getRandom(10, 2)
        await insertData('user', {
            tel: tel,
            captcha: captcha,
            avatar: avatar,
            nickname: nickname,
            fans: fans,
            follow: follow
        })
        resp.json({
            code: 200,
            msg: '验证码获取成功！',
            data: captcha
        })
    },
    // 登录：获取手机号和验证码进行校验，返回token、个人信息（头像、昵称、粉丝数、关注数）
    async login(req, resp) {
        const {tel, captcha} = req.body
        let data = await getData('user', `tel=${tel} and captcha=${captcha}`)
        if (data.length === 0) {
            resp.json({
                code: 402,
                msg: '验证码错误！'
            })
            return
        }
        resp.json({
            code: 200,
            msg: '登录成功！',
            data: {
                token: jwt.sign({
                    a: 1,
                    b: 2
                }, 'zxdvafasd'),
                userInfo: data[0]
            }
        })
    }
}